Page({
  data: {
    orderNo: '',
    amount: 0,
    subject: '',
    qrCodeUrl: '',
    qrCodeImageUrl: '',
    loading: true,
    paymentStatus: 'unpaid' // unpaid, paid, failed
  },

  onLoad(options) {
    console.log('支付页面参数:', options);
    
    // 从本地存储获取支付数据
    const paymentData = wx.getStorageSync('paymentData');
    const currentOrderId = wx.getStorageSync('currentOrderId');
    
    if (paymentData && currentOrderId) {
      this.setData({
        orderNo: paymentData.orderNo || '',
        amount: paymentData.amount || 0,
        subject: paymentData.subject || '',
        qrCodeUrl: paymentData.paymentUrl || ''
      });
      
      this.generateQRCode();
      this.startPaymentStatusCheck();
    } else {
      wx.showToast({
        title: '支付数据错误',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 生成二维码
  generateQRCode() {
    const { qrCodeUrl } = this.data;
    
    if (!qrCodeUrl) {
      wx.showToast({
        title: '支付链接为空',
        icon: 'error'
      });
      return;
    }

    // 打印支付链接用于调试
    console.log('生成的支付链接:', qrCodeUrl);
    
    // 显示支付链接供调试
    wx.showModal({
      title: '调试信息',
      content: `支付链接: ${qrCodeUrl.substring(0, 100)}...`,
      showCancel: true,
      confirmText: '继续',
      cancelText: '复制链接',
      success: (res) => {
        if (res.cancel) {
          // 用户选择复制链接
          wx.setClipboardData({
            data: qrCodeUrl,
            success: () => {
              wx.showToast({
                title: '链接已复制',
                icon: 'success'
              });
            }
          });
        }
        // 继续生成二维码
        this.createQRCode();
      }
    });
  },

  // 创建二维码
  createQRCode() {
    const { qrCodeUrl } = this.data;
    
    // 使用多个二维码生成服务作为备选
    const qrServices = [
      `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(qrCodeUrl)}`,
      `https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=${encodeURIComponent(qrCodeUrl)}`,
      `https://qr-server.com/api/v1/create-qr-code/?size=300&data=${encodeURIComponent(qrCodeUrl)}`
    ];

    this.tryGenerateQRCode(qrServices, 0);
  },

  // 尝试生成二维码
  tryGenerateQRCode(qrServices, index) {
    if (index >= qrServices.length) {
      wx.showToast({
        title: '二维码生成失败',
        icon: 'error'
      });
      this.setData({ loading: false });
      return;
    }

    const qrUrl = qrServices[index];
    console.log(`尝试生成二维码 ${index + 1}:`, qrUrl);

    // 测试图片是否可以加载
    wx.request({
      url: qrUrl,
      method: 'HEAD',
      success: (res) => {
        if (res.statusCode === 200) {
          console.log('二维码生成成功:', qrUrl);
          this.setData({
            qrCodeImageUrl: qrUrl,
            loading: false
          });
        } else {
          this.tryGenerateQRCode(qrServices, index + 1);
        }
      },
      fail: () => {
        this.tryGenerateQRCode(qrServices, index + 1);
      }
    });
  },

  // 开始检查支付状态
  startPaymentStatusCheck() {
    this.statusCheckTimer = setInterval(() => {
      this.checkPaymentStatus();
    }, 3000); // 每3秒检查一次
  },

  // 检查支付状态
  checkPaymentStatus() {
    const token = wx.getStorageSync('token');
    const currentOrderId = wx.getStorageSync('currentOrderId');
    const orderNo = this.data.orderNo;
    
    if (!token || !currentOrderId || !orderNo) {
      return;
    }

    // 判断是VIP订单还是产品订单
    const paymentData = wx.getStorageSync('paymentData');
    const isVipOrder = paymentData && paymentData.subject && (
      paymentData.subject.includes('日套餐') || 
      paymentData.subject.includes('周套餐') || 
      paymentData.subject.includes('月套餐') ||
      paymentData.subject.includes('VIP')
    );

    // 根据订单类型调用不同的API
    const apiUrl = isVipOrder 
      ? `http://localhost:8081/api/alipay/checkPaymentStatus?orderNo=${orderNo}`
      : `http://localhost:8081/api/productpay/checkPaymentStatus?orderNo=${orderNo}`;

    console.log('检查支付状态，订单类型:', isVipOrder ? 'VIP订单' : '产品订单');
    console.log('API地址:', apiUrl);

    // 通过支付宝接口检查支付状态
    wx.request({
      url: apiUrl,
      method: 'GET',
      header: {
        'token': token
      },
      success: (res) => {
        console.log('支付宝支付状态检查响应:', res.data);
        
        if (res.data && res.data.code === 200) {
          if (res.data.status === 'paid') {
            // 支付成功
            this.setData({ paymentStatus: 'paid' });
            this.onPaymentSuccess();
          } else {
            // 未支付，继续等待
            console.log('订单未支付，继续等待...');
          }
        }
      },
      fail: (err) => {
        console.error('支付宝支付状态检查失败:', err);
        // 如果支付宝接口失败，回退到原来的方法
        this.checkOrderStatusFromDatabase();
      }
    });
  },

  // 从数据库检查订单状态（备用方法）
  checkOrderStatusFromDatabase() {
    const token = wx.getStorageSync('token');
    const currentOrderId = wx.getStorageSync('currentOrderId');
    
    if (!token || !currentOrderId) {
      return;
    }

    // 判断是VIP订单还是产品订单
    const paymentData = wx.getStorageSync('paymentData');
    const isVipOrder = paymentData && paymentData.subject && (
      paymentData.subject.includes('日套餐') || 
      paymentData.subject.includes('周套餐') || 
      paymentData.subject.includes('月套餐') ||
      paymentData.subject.includes('VIP')
    );

    // 根据订单类型调用不同的API
    const apiUrl = isVipOrder 
      ? `http://localhost:8081/viporder/getById?id=${currentOrderId}`
      : `http://localhost:8081/order/getById?id=${currentOrderId}`;

    console.log('数据库状态检查，订单类型:', isVipOrder ? 'VIP订单' : '产品订单');
    console.log('API地址:', apiUrl);

    // 检查订单状态
    wx.request({
      url: apiUrl,
      method: 'GET',
      header: {
        'token': token
      },
      success: (res) => {
        console.log('数据库订单状态检查响应:', res.data);
        
        if (res.data) {
          // VIP订单状态检查
          if (isVipOrder && res.data.status === 1) {
            this.setData({ paymentStatus: 'paid' });
            this.onPaymentSuccess();
          }
          // 产品订单状态检查
          else if (!isVipOrder && res.data.code === 200 && res.data.data) {
            const order = res.data.data;
            if (order.status === 'paid') {
              this.setData({ paymentStatus: 'paid' });
              this.onPaymentSuccess();
            } else if (order.status === 'cancelled') {
              this.setData({ paymentStatus: 'cancelled' });
              console.log('订单已取消');
            } else {
              console.log('订单未支付，继续等待...');
            }
          }
        }
      },
      fail: (err) => {
        console.error('数据库订单状态检查失败:', err);
      }
    });
  },

  // 支付成功处理
  onPaymentSuccess() {
    if (this.statusCheckTimer) {
      clearInterval(this.statusCheckTimer);
    }

    // 根据订单类型显示不同的成功消息和跳转逻辑
    const paymentData = wx.getStorageSync('paymentData');
    const isVipOrder = paymentData && paymentData.subject && (
      paymentData.subject.includes('日套餐') || 
      paymentData.subject.includes('周套餐') || 
      paymentData.subject.includes('月套餐') ||
      paymentData.subject.includes('VIP')
    );
    
    const successMessage = isVipOrder 
      ? '您的VIP会员已激活，感谢您的购买！'
      : '支付成功，感谢您的购买！';

    wx.showModal({
      title: '支付成功',
      content: successMessage,
      showCancel: false,
      success: () => {
        // 清除本地存储
        wx.removeStorageSync('paymentData');
        wx.removeStorageSync('currentOrderId');
        
        // 根据订单类型跳转到不同页面
        if (isVipOrder) {
          // VIP订单支付成功，跳转到会员页面
          wx.redirectTo({
            url: '/pages/membership/membership',
            success: () => {
              console.log('跳转到会员页面成功');
            },
            fail: (err) => {
              console.error('跳转到会员页面失败:', err);
              wx.navigateBack();
            }
          });
        } else {
          // 产品订单支付成功，跳转到订单列表页面
          wx.redirectTo({
            url: '/pages/order/order',
            success: () => {
              console.log('跳转到订单列表页面成功');
            },
            fail: (err) => {
              console.error('跳转到订单列表页面失败:', err);
              wx.navigateBack();
            }
          });
        }
      }
    });
  },

  // 取消支付
  onCancelPayment() {
    wx.showModal({
      title: '取消支付',
      content: '确定要取消支付吗？',
      success: (res) => {
        if (res.confirm) {
          if (this.statusCheckTimer) {
            clearInterval(this.statusCheckTimer);
          }
          
          // 清除本地存储
          wx.removeStorageSync('paymentData');
          wx.removeStorageSync('currentOrderId');
          
          wx.navigateBack();
        }
      }
    });
  },

  // 重新生成二维码
  onRegenerateQR() {
    this.setData({ loading: true });
    this.generateQRCode();
  },


  onUnload() {
    // 页面卸载时清除定时器
    if (this.statusCheckTimer) {
      clearInterval(this.statusCheckTimer);
    }
  }
});
